package cn.bdqn.dao.impl;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

import cn.bdqn.dao.BaseDao;
import cn.bdqn.dao.NewsCategoryDao;
import cn.bdqn.pojo.NewsCategory;

public class NewsCategoryDaoImpl extends BaseDao implements NewsCategoryDao {

	/**
	 * (级联删除)
	 * 删除新闻类别：若该类别在新闻明细表中有数据，那么先删除新闻明细表中的数据
	 * 若无，直接删除该类别
	 */
	@Override
	public boolean delNewsCategory(NewsCategory newsCategory) {
		// TODO Auto-generated method stub
		boolean flag = false;
		String delNewsDetailSql = "delete from news_detail where categoryId=?";
		String delNewsCategorySql = "delete from news_category where id=?";
		Object[] params = {newsCategory.getId()};
		
		if(this.getConnection()){
			//先删子表（news_detail），再删主表（news_category）
			int i = this.executeUpdate(delNewsDetailSql, params);
			if(i != -1){
				int j = this.executeUpdate(delNewsCategorySql, params);
				if(j > 0){
					System.out.println("删除新闻类别成功！");
					flag = true;
				}
			}
		}
		this.closeResource();
		return flag;
	}

	@Override
	public List<NewsCategory> getNewsCategoryList() {
		// TODO Auto-generated method stub
		List<NewsCategory> newsCategoryList= new ArrayList<NewsCategory>();
		String sql = "select * from news_category";
		Object[] params = {};
		if(this.getConnection()){
			try {
				ResultSet rs = this.executeQuery(sql, params);
				while(rs.next()){
					NewsCategory newsCategory = new NewsCategory();
					newsCategory.setId(rs.getInt("id"));
					newsCategory.setName(rs.getString("name"));
					newsCategory.setCreateDate(rs.getTimestamp("createDate"));
					
					newsCategoryList.add(newsCategory);
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}finally{
				this.closeResource();
			}
			
		}
		return newsCategoryList;
	}

}
